/*******************************************************************
 *
 * Copyright (C), 2021-2022, LS, All rights reserved.
 *
 * Author      : 
 * Create Time : 2021-09-17
 * Version     : v0.1
 * Description : 
 *******************************************************************/

 /*
 * INCLUDE FILES
 ****************************************************************************************
 */
#include <string.h>
#include "bcomdef.h"
#include "OSAL.h"
#include "linkdb.h"
#include "att.h"
#include "gatt.h"
#include "gatt_uuid.h"
#include "peripheral.h"
#include "gattservapp.h"
#include "ls_ble_type.h"
#include "ls_ble_custom.h"
#include "ls_ble_sdk_config.h"
#include "osal_ble.h"

/*
 * DEFINES
 ****************************************************************************************
 */
#define CUSTOM_PROTO_LOG_EN     1

#if CUSTOM_PROTO_LOG_EN
#include "ls_ble_log.h"
#define CUSTOM_LOG(...)         LS_BLE_LOG_RAW_INFO(__VA_ARGS__)
#else
#define CUSTOM_LOG(...)
#endif

/*********************************************************************
 * MACROS
 */
 
#define CUSTOM_INDICATE_HANDLE	4

/*********************************************************************
 * CONSTANTS
 */


/*********************************************************************
 * TYPEDEFS
 */

/*********************************************************************
 * GLOBAL VARIABLES
 */
// CUSTOM GATT Profile Service UUID
CONST uint8 customServUUID[ATT_BT_UUID_SIZE] =
{
    LO_UINT16(CUSTOM_SERVICE_UUID), HI_UINT16(CUSTOM_SERVICE_UUID)
};

// CUSTOM Characteristic Write response UUID: 0xFFB1
CONST uint8 customProfilecharWriteUUID[ATT_BT_UUID_SIZE] =
{ 
    LO_UINT16(CUSTOM_SERVICE_WRITE_UUID), HI_UINT16(CUSTOM_SERVICE_WRITE_UUID)
};

// CUSTOM Characteristic Indication UUID: 0xFFB2
CONST uint8 customProfilecharIndicateUUID[ATT_BT_UUID_SIZE] =
{ 
    LO_UINT16(CUSTOM_SERVICE_INDICATE_UUID), HI_UINT16(CUSTOM_SERVICE_INDICATE_UUID)
};

/*********************************************************************
 * EXTERNAL VARIABLES
 */

/*********************************************************************
 * EXTERNAL FUNCTIONS
 */

/*********************************************************************
 * LOCAL VARIABLES
 */

/*********************************************************************
 * Profile Attributes - variables
 */

// CUSTOM Profile Service attribute
static CONST gattAttrType_t customProfileService = { ATT_BT_UUID_SIZE, customServUUID };


// CUSTOM Profile Characteristic 1 Properties
static uint8 customProfileCharWriteProps = GATT_PROP_WRITE;

// CUSTOM Characteristic write Value
static uint8 customProfileCharWirte[CUSTOM_MAX_DATA_LEN];

static gattCharCfg_t customProfileCmdCCC[GATT_MAX_NUM_CONN];

// CUSTOM Profile Indicate Characteristic Properties
static uint8 customProfileCharIndicateProps = GATT_PROP_INDICATE | GATT_PROP_READ;

// CUSTOM Characteristic Indicate Value
static uint8 customProfileCharIndicate[CUSTOM_MAX_DATA_LEN];


static custom_profile_cb_t *custom_profile_cb = NULL;

/*********************************************************************
 * Profile Attributes - Table
 */

static gattAttribute_t customProfileAttrTbl[] = 
{
    // CUSTOM Profile Service
    { 
        { ATT_BT_UUID_SIZE, primaryServiceUUID }, /* type */
        GATT_PERMIT_READ,                         /* permissions */
        0,                                        /* handle */
        (uint8 *)&customProfileService            /* pValue */
    },

    // Command Characteristic Declaration
    { 
        { ATT_BT_UUID_SIZE, characterUUID },
        GATT_PERMIT_READ, 
        0,
        &customProfileCharWriteProps 
    },

        // CUSTOM Characteristic Write Value
        { 
            { ATT_BT_UUID_SIZE, customProfilecharWriteUUID },
            GATT_PERMIT_READ | GATT_PERMIT_WRITE,
            0, 
            &customProfileCharWirte[0]
        },


    // CUSTOM Characteristic readonly Declaration
    { 
        { ATT_BT_UUID_SIZE, characterUUID },
        GATT_PERMIT_READ,
        0,
        &customProfileCharIndicateProps 
    },

        // CUSTOM Characteristic Indicate Value
        {
            { ATT_BT_UUID_SIZE, customProfilecharIndicateUUID },
            GATT_PERMIT_READ | GATT_PERMIT_WRITE, 
            0, 
            &customProfileCharIndicate[0] 
        },
        
        // CUSTOM Characteristic Indicate configuration
        {
            { ATT_BT_UUID_SIZE, clientCharCfgUUID },
            GATT_PERMIT_READ | GATT_PERMIT_WRITE, 
            0, 
            (uint8 *)customProfileCmdCCC 
        },
};

/*********************************************************************
 * LOCAL FUNCTIONS
 */
static uint8 customProfile_ReadAttrCB( uint16 connHandle, gattAttribute_t *pAttr, uint8 *pValue, uint16 *pLen, uint16 offset, uint8 maxLen );
static bStatus_t customProfile_WriteAttrCB( uint16 connHandle, gattAttribute_t *pAttr, uint8 *pValue, uint16 len, uint16 offset );

/*********************************************************************
 * PROFILE CALLBACKS
 */
// CUSTOM Profile Service Callbacks
CONST gattServiceCBs_t customProfileCBs =
{
    customProfile_ReadAttrCB,  // Read callback function pointer
    customProfile_WriteAttrCB, // Write callback function pointer
    NULL                       // Authorization callback function pointer
};

/*********************************************************************
 * PUBLIC FUNCTIONS
 */

/*********************************************************************
 * @fn      customProfile_AddService
 *
 * @brief   Initializes the Rope Profile service by registering
 *          GATT attributes with the GATT server.
 *
 * @param   services - services to add. This is a bit map and can
 *                     contain more than one service.
 *
 * @return  Success or Failure
 */
int custom_service_init(custom_profile_cb_t *cb)
{
	uint8 status = SUCCESS;

	// Initialize Client Characteristic Configuration attributes
	GATTServApp_InitCharCfg( INVALID_CONNHANDLE, customProfileCmdCCC );

	// Register GATT attribute list and CBs with GATT Server App
	status = GATTServApp_RegisterService( customProfileAttrTbl, 
										  GATT_NUM_ATTRS( customProfileAttrTbl ),
										  &customProfileCBs );
    if(cb)
    {
        custom_profile_cb = cb;
        return ( SUCCESS );
    }
    
	return ( status );
}


/*********************************************************************
 * @fn          customProfile_ReadAttrCB
 *
 * @brief       Read an attribute.
 *
 * @param       connHandle - connection message was received on
 * @param       pAttr - pointer to attribute
 * @param       pValue - pointer to data to be read
 * @param       pLen - length of data to be read
 * @param       offset - offset of the first octet to be read
 * @param       maxLen - maximum length of data to be read
 *
 * @return      Success or Failure
 */
//static int count = 0;
static uint8 customProfile_ReadAttrCB( uint16 connHandle, gattAttribute_t *pAttr, uint8 *pValue, uint16 *pLen, uint16 offset, uint8 maxLen )
{
    bStatus_t status = SUCCESS;

    // If attribute permissions require authorization to read, return error
    if ( gattPermitAuthorRead( pAttr->permissions ) )
    {
        // Insufficient authorization
        return ( ATT_ERR_INSUFFICIENT_AUTHOR );
    }

    // Make sure it's not a blob operation (no attributes in the profile are long)
    if ( offset > 0 )
    {
        return ( ATT_ERR_ATTR_NOT_LONG );
    }

    if ( pAttr->type.len == ATT_BT_UUID_SIZE )
    {
        // 16-bit UUID
        uint16 uuid = BUILD_UINT16( pAttr->type.uuid[0], pAttr->type.uuid[1]);
        switch ( uuid )
        {
            //Clark add
            /*case CUSTOM_SERVICE_INDICATE_UUID: {
                uint8_t test[20];
                for(int i=0;i<20;i++) {
                    test[i] = i + count;
                }
                *pLen = 20;
                VOID osal_memcpy( pValue, test, 20 );
                count++;
            } break;*/
            
            default:
                // Should never get here! (characteristics 3 and 4 do not have read permissions)
                *pLen = 0;
                status = ATT_ERR_ATTR_NOT_FOUND;
            break;
        }
    }
    else
    {
        // 128-bit UUID
        *pLen = 0;
        status = ATT_ERR_INVALID_HANDLE;
    }

    return ( status );
}

/*********************************************************************
 * @fn      customProfile_WriteAttrCB
 *
 * @brief   Validate attribute data prior to a write operation
 *
 * @param   connHandle - connection message was received on
 * @param   pAttr - pointer to attribute
 * @param   pValue - pointer to data to be written
 * @param   len - length of data
 * @param   offset - offset of the first octet to be written
 *
 * @return  Success or Failure
 */
static bStatus_t customProfile_WriteAttrCB( uint16 connHandle, gattAttribute_t *pAttr, uint8 *pValue, uint16 len, uint16 offset )
{
	bStatus_t status = SUCCESS;
    custom_evt_t evt = {
        .evt_type = CUSTOM_EVT_INVALID,
        .length = 0
    };

    // If attribute permissions require authorization to write, return error
    if( gattPermitAuthorWrite( pAttr->permissions ) )
    {
        // Insufficient authorization
        return ( ATT_ERR_INSUFFICIENT_AUTHOR );
    }

    if( pAttr->type.len == ATT_BT_UUID_SIZE )
    {
		// 16-bit UUID
        uint16 uuid = BUILD_UINT16( pAttr->type.uuid[0], pAttr->type.uuid[1]);
        switch ( uuid )
        {
            case CUSTOM_SERVICE_WRITE_UUID: {
                evt.evt_type = CUSTOM_EVT_RECEIVE_DATA;
                evt.length = len;
                evt.p_data = pValue;
            } break;

            case GATT_CLIENT_CHAR_CFG_UUID: {
                status = GATTServApp_ProcessCCCWriteReq(connHandle, pAttr, pValue, len, offset, GATT_CLIENT_CFG_INDICATE);
                if(status == SUCCESS)
                {
                    uint16 charCfg = BUILD_UINT16(pValue[0], pValue[1]);
                    evt.evt_type = (charCfg == GATT_CFG_NO_OPERATION) ? CUSTOM_EVT_INDICATION_DISABLED : CUSTOM_EVT_INDICATION_ENABLED;
                }
            } break;

            default:
                // Should never get here! (characteristics 2 and 4 do not have write permissions)
                status = ATT_ERR_ATTR_NOT_FOUND;
            break;
        }
    }
    else
    {
        // 128-bit UUID
        status = ATT_ERR_INVALID_HANDLE;
    }

    if(custom_profile_cb && CUSTOM_EVT_INVALID != evt.evt_type) {
        custom_profile_cb->evt_handler(&evt);
    }

    return ( status );
}

/*********************************************************************
 * @fn          customProfile_HandleConnStatusCB
 *
 * @brief       Rope Profile link status change handler function.
 *
 * @param       connHandle - connection handle
 * @param       changeType - type of change
 *
 * @return      none
 */
void customProfile_HandleConnStatusCB( uint16 connHandle, uint8 changeType )
{ 
    // Make sure this is not loopback connection
    if ( connHandle != LOOPBACK_CONNHANDLE )
    {
        // Reset Client Char Config if connection has dropped
        if ( ( changeType == LINKDB_STATUS_UPDATE_REMOVED )      ||
             ( ( changeType == LINKDB_STATUS_UPDATE_STATEFLAGS ) && 
               ( !linkDB_Up( connHandle ) ) ) )
        { 
            GATTServApp_InitCharCfg( connHandle, customProfileCmdCCC );
        }
    }
}


int custom_indicate_data(uint8_t *p_data, uint16_t length)
{
    uint16 value;
    uint16 connHandle;
    attHandleValueInd_t ind;

    if(length > ATT_MTU_SIZE) {
        return LS_BLE_ERR_INVALID_LENGTH;
    }

    GAPRole_GetParameter(GAPROLE_CONNHANDLE, &connHandle);
    value = GATTServApp_ReadCharCfg( connHandle, customProfileCmdCCC);

    // If indication enabled
    if( value & GATT_CLIENT_CFG_INDICATE )
    {
        // Set the handle
        ind.handle = customProfileAttrTbl[CUSTOM_INDICATE_HANDLE].handle;
        memcpy(ind.value, p_data, length);
        ind.len = length;
        //CUSTOM_LOG("Indication\n");

        // Send the indication
        bStatus_t st = GATT_Indication(connHandle, &ind, FALSE, osalBle_TaskID);
        if(st != SUCCESS)
        {
            CUSTOM_LOG("st: %d\n", st);
        }
        else {
            return LS_BLE_SUCCESS;
        }
    }

    return LS_BLE_ERR_IND_FAIL;
}


void custom_set_profile_cb_evt(uint8_t type)
{
    custom_evt_t evt = {
        .evt_type = type,
        .length = 0
    };
    if(custom_profile_cb && CUSTOM_EVT_INVALID != evt.evt_type) {
        custom_profile_cb->evt_handler(&evt);
    }
}
